#include <unistd.h>

struct tagid_name
{
	unsigned int id;
	char name[256];	
};

struct inode_name
{
	unsigned int inode;
	char name[256];
};

void get_system_filepath(char* filename, char* result)
{
	strcpy(result, "/home/");
	strcat(result, getlogin());
	strcat(result, filename);

	//debug location
	//strcpy(result, "/home/tonyoot/Desktop/tagfs/debug");
	//strcat(result, filename);
}

// clean . and .. in path -> e.g., /home/ton/a/./b -> /home/ton/a/b
void clean_path(char* path)
{
	char *tmp;
	char *tmp2;
	char *tmp3;
	while(1)
	{
		if((tmp = strstr(path, "/./")) != NULL)
		{
			memmove(tmp, tmp+2, (strlen(tmp)-1)*sizeof(char)); // also move '\0'
		}
		else if((tmp = strstr(path, "/../")) != NULL)
		{
			tmp2 = (char*)malloc((strlen(path)+1)*sizeof(char));
			strcpy(tmp2, path);
			tmp3 = strstr(tmp2, "/../");
			tmp3[0] = '\0';
			tmp3 = strrchr(tmp2, '/');
			memmove(tmp-strlen(tmp3), tmp+3, (strlen(tmp)-2)*sizeof(char)); // also move '\0'
		}
		else
		{
			break;
		}
	}
}

// file print code - for debugging
void print_tagid_tagname()
{
	FILE* fp;
	struct tagid_name* entry;
	int num, i;
	char system_filepath[256];
	entry = (struct tagid_name *)malloc(sizeof(struct tagid_name));
	get_system_filepath("/.tagid_tagname", system_filepath);
	printf("== .tagid_tagname ==\n");
	fp = fopen(system_filepath, "rb");
	fseek(fp, 0, SEEK_END);	
	num = ftell(fp)/sizeof(struct tagid_name);
	fseek(fp, 0, SEEK_SET);
	for(i=0; i<num; i++)	
	{
		fread(entry, sizeof(struct tagid_name), 1, fp);
		printf("%u %s\n", entry->id, entry->name);
	}
	fclose(fp);
	free(entry);
}

void print_inode_name()
{
	FILE* fp;
	struct inode_name* entry;
	int num, i;
	char system_filepath[256];
	entry = (struct inode_name *)malloc(sizeof(struct inode_name));
	get_system_filepath("/.inode_name", system_filepath);
	printf("== .inode_name ==\n");
	fp = fopen(system_filepath, "rb");
	fseek(fp, 0, SEEK_END);	
	num = ftell(fp)/sizeof(struct inode_name);
	fseek(fp, 0, SEEK_SET);
	for(i=0; i<num; i++)	
	{
		fread(entry, sizeof(struct inode_name), 1, fp);
		printf("%u %s\n", entry->inode, entry->name);
	}
	fclose(fp);
	free(entry);
}

void print_tagid_inode()
{
	FILE* fp;
	unsigned int entry;
	int num, i;
	char system_filepath[256];
	get_system_filepath("/.tagid_inode", system_filepath);
	printf("== .tagid_inode ==\n");
	fp = fopen(system_filepath, "rb");
	fseek(fp, 0, SEEK_END);	
	num = ftell(fp)/sizeof(unsigned int);
	fseek(fp, 0, SEEK_SET);
	for(i=0; i<num; i++)	
	{
		fread(&entry, sizeof(unsigned int), 1, fp);
		printf("%u\n", entry);
	}
	fclose(fp);
}

void print_inode_tagid()
{
	FILE* fp;
	unsigned int entry;
	int num, i;
	char system_filepath[256];
	get_system_filepath("/.inode_tagid", system_filepath);
	printf("== .inode_tagid ==\n");
	fp = fopen(system_filepath, "rb");
	fseek(fp, 0, SEEK_END);	
	num = ftell(fp)/sizeof(unsigned int);
	fseek(fp, 0, SEEK_SET);
	for(i=0; i<num; i++)	
	{
		fread(&entry, sizeof(unsigned int), 1, fp);
		printf("%u\n", entry);
	}
	fclose(fp);
}
